var _ThunderNoteXUL='chrome://thundernote/content/thundernoteNote.xul';
var _ThunderNoteHelpXUL='chrome://thundernote/content/thundernoteHelp.xul';
var _ThunderNoteConfigXUL='chrome://thundernote/content/thundernoteConfig.xul';
var _ThunderNotePrintXUL='chrome://thundernote/content/thundernotePrint.xul';
var _ThunderNotePrintTemplate='chrome://thundernote/content/ThunderNoteTemplate.html';
var _ThunderNoteNotesFileName='ThunderNotes.xml';
var _ThunderNoteCategoriesFileName='ThunderNoteCategories.xml';
var _ThunderNoteConfigFileName='ThunderNoteConfig.xml';
var _ThunderNoteSyncDBFileName='ThunderNoteSyncDB.xml';
var _ThunderNoteSyncXUL='chrome://thundernote/content/thundernoteSync.xul';
var _ThunderNoteMaxNoteSize=4000;

const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

// debug stuff from http://developer.mozilla.org/en/docs/Debugging_a_XULRunner_Application
function javaConsoleMessage(str)
{
  Components.classes['@mozilla.org/consoleservice;1']
            .getService(Components.interfaces.nsIConsoleService)
            .logStringMessage(str);
}

function javaConsoleError(str)
{
  Components.utils.reportError('err');
}

function consoleMessage(str)
{
  dump(str);
}

// common functions

// from http://www.somacon.com/p355.php
//------------------------------------------------------------
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
//------------------------------------------------------------

function checkNodeIndex(xmlNode,idx,fieldName)
{
  var children=xmlNode.childNodes;
  var _idx='';
  
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName==fieldName)
      _idx=getXMLNodeValue(children[x]);
  }

  if(_idx==idx)
    return(true);
  else
    return(false);  
}

function getNamedNodeValue(xmlNode,nodeName)
{
  var children=xmlNode.childNodes;
  var RetVal='';
  
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName==nodeName)
      RetVal=getXMLNodeValue(children[x]);
  }
  
  return(RetVal);
}

function getXMLNodeValue(xmlNode)
{
  var children=xmlNode.childNodes;
  var RetVal='';
  
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='#text')
    {
      RetVal=children[x].nodeValue;
      break;
    }
  }
  
  return(RetVal);
}

function alertXML(xmlNode)
{
  var serializer = new XMLSerializer();
  var prettyString = XML(serializer.serializeToString(xmlNode)).toXMLString();
  alert(prettyString);
}

function readCategoriesVersion()
{
  var dom=readCategories();
  var RetVal=0;
  
  if(dom!=null)
  {
    if(dom.documentElement.getAttribute('version')!=null)
      RetVal=dom.documentElement.getAttribute('version');
  }
  
  return(RetVal);
}

function readConfigVersion()
{
  var dom=readConfig();
  var RetVal=0;
  
  if(dom!=null)
  {
    if(dom.documentElement.getAttribute('version')!=null)
      RetVal=dom.documentElement.getAttribute('version');
  }
  
  return(RetVal);
}

function readThunderNotesVersion()
{
  var dom=readThunderNotes();
  var RetVal=0;
  
  if(dom!=null)
  {
    if(dom.documentElement.getAttribute('version')!=null)
      RetVal=dom.documentElement.getAttribute('version');
  }
  
  return(RetVal);
}

function readSyncDBVersion()
{
  var dom=readSyncDB();
  var RetVal=0;
  
  if(dom!=null)
  {
    if(dom.documentElement.getAttribute('version')!=null)
      RetVal=dom.documentElement.getAttribute('version');
  }
  
  return(RetVal);
}

function readThunderNotes()
{
  return(readThunderNoteFile(_ThunderNoteNotesFileName));
}

function readCategories()
{
  return(readThunderNoteFile(_ThunderNoteCategoriesFileName));
}

function readConfig()
{
  return(readThunderNoteFile(_ThunderNoteConfigFileName));
}

function readSyncDB()
{
  return(readThunderNoteFile(_ThunderNoteSyncDBFileName));
}

function readThunderNoteFile(fileName)
{
  var file = Components.classes["@mozilla.org/file/directory_service;1"]
             .getService(Components.interfaces.nsIProperties)
             .get('ProfD', Components.interfaces.nsIFile);
  file.append(fileName);
  var x=FileIO.read(file);
  
  var parser = new DOMParser();
  var doc = parser.parseFromString(x,"text/xml");

  
  return(doc);
}

function readRawThunderNoteFile(fileName)
{
  //http://developer.mozilla.org/en/docs/Parsing_and_serializing_XML
  var RetVal=null;
  var req = new XMLHttpRequest();
  req.open('GET', fileName, false); 
  req.send(null);
  RetVal = req.responseText;
  
  return(RetVal);
}

function writeThunderNotes(dom)
{
  writeThunderNoteFile(dom,_ThunderNoteNotesFileName);
}

function writeCategories(dom)
{
  writeThunderNoteFile(dom,_ThunderNoteCategoriesFileName);
}

function writeConfig(dom)
{
  writeThunderNoteFile(dom,_ThunderNoteConfigFileName);
}

function writeSyncDB(dom)
{
  writeThunderNoteFile(dom,_ThunderNoteSyncDBFileName);
}

function deleteFile(fileName)
{
  var file = Components.classes["@mozilla.org/file/directory_service;1"]
             .getService(Components.interfaces.nsIProperties)
             .get('ProfD', Components.interfaces.nsIFile);  // profile root folder
  file.append("extensions");                                // extensions sub-directory
  file.append("thundernote@thundernote.com");               // GUID of your extension

  file.append('chrome');
  file.append(fileName);
  file.remove(false);
}

function copyFile(oldFileName,newFileName)
{
  var file = Components.classes["@mozilla.org/file/directory_service;1"]
             .getService(Components.interfaces.nsIProperties)
             .get('ProfD', Components.interfaces.nsIFile);  // profile root folder
  file.append("extensions");                                // extensions sub-directory
  file.append("thundernote@thundernote.com");               // GUID of your extension

  file.append('chrome');
  file.append(oldFileName);
  file.copyTo(null,newFileName);

  var file2 = Components.classes["@mozilla.org/file/directory_service;1"]
             .getService(Components.interfaces.nsIProperties)
             .get('ProfD', Components.interfaces.nsIFile);  // profile root folder
  file2.append("extensions");                                // extensions sub-directory
  file2.append("thundernote@thundernote.com");               // GUID of your extension

  file2.append('chrome');
  file2.append(newFileName);
  FileIO.write(file2,'\r\n<!--comment to update file date/time-->','a');
}

function dataFileExists(fileName)
{
  var file = Components.classes["@mozilla.org/file/directory_service;1"]
             .getService(Components.interfaces.nsIProperties)
             .get('ProfD', Components.interfaces.nsIFile);
  file.append(fileName);
  
  return(file.exists());
}

function createDataFile(oldFileName,newFileName)
{
  var file = Components.classes["@mozilla.org/file/directory_service;1"]
             .getService(Components.interfaces.nsIProperties)
             .get('ProfD', Components.interfaces.nsIFile);
  file.append("extensions");                                // extensions sub-directory
  file.append("thundernote@thundernote.com");               // GUID of your extension

  file.append('chrome');
  file.append(oldFileName);

  var file2 = Components.classes["@mozilla.org/file/directory_service;1"]
             .getService(Components.interfaces.nsIProperties)
             .get('ProfD', Components.interfaces.nsIFile);

  file.copyTo(file2,newFileName);
}

function writeThunderNoteFile(dom,fileName)
{
  // from http://developer.mozilla.org/en/docs/Parsing_and_serializing_XML
  var serializer = new XMLSerializer();
  var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
                 .createInstance(Components.interfaces.nsIFileOutputStream);
  
  //var file = Components.classes["@mozilla.org/file/directory_service;1"]
  //           .getService(Components.interfaces.nsIProperties)
  //           .get('resource:app', Components.interfaces.nsIFile);  // profile root folder

  var file = Components.classes["@mozilla.org/file/directory_service;1"]
             .getService(Components.interfaces.nsIProperties)
             .get('ProfD', Components.interfaces.nsIFile);  // profile root folder

  file.append(fileName);                                    // filename
  foStream.init(file, 0x02 | 0x08 | 0x20, 0664, 0);         // write, create, truncate
  serializer.serializeToStream(dom, foStream, "");          // rememeber, doc is the DOM tree
  foStream.close();
}

function getJarFileLocalPath(jarName)
{
  //var file = Components.classes["@mozilla.org/file/directory_service;1"]
  //           .getService(Components.interfaces.nsIProperties)
  //           .get('resource:app', Components.interfaces.nsIFile);  // profile root folder

  var file = Components.classes["@mozilla.org/file/directory_service;1"]
             .getService(Components.interfaces.nsIProperties)
             .get('ProfD', Components.interfaces.nsIFile);  // profile root folder
  file.append("extensions");                                // extensions sub-directory
  file.append("thundernote@thundernote.com");               // GUID of your extension

  file.append("components");                                    // component sub-directory
  file.append(jarName);                                       // filename
  return(file.path);
}

function getTitle(note)
{
  var RetVal='';
  var idx=note.search('\n');
  
  if(idx!=-1)
    RetVal=note.substring(0,idx);
  else
    RetVal=note;
  RetVal=RetVal.trim();

  return(RetVal);
}

function getBody(note)
{
  var RetVal='';
  var idx=note.search('\n');
  
  if(idx!=-1)
    RetVal=note.substring(idx);
    
  return(RetVal);
}

function getSerializeNode(xmlNode)
{
  var serializer = new XMLSerializer();
  var prettyString = XML(serializer.serializeToString(xmlNode)).toXMLString();

  return(prettyString);
}